<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>websocket</title>
	<script src="./socket.io.min.js"></script>
</head>
<body>
	<div id="login">
		<input type="text" placeholder="请输入您的昵称！"/>
	</div>
	<div id="room" style="display: none">
		<p>欢迎<span id="username" style="color:red"></span>到来，当前在线人数为：<span id="online" style="color:green"></span></p>
		<input id="content" type="text"/><br/><br/>
		<textarea id="chat" rows="30" cols="70"></textarea>
	</div>
</body>
<script>
	// 登陆
	document.querySelector("#login input").onkeyup = function(e){
        console.log(444444444)
        if(e.keyCode === 13){
            console.log(3333)
            const username = this.value.trim();
            if(username.length===0){
                alert("请输入用户名");
                return;
            }
            fetch("/login",{
                method:"post",
                headers:{
                    "Content-Type":"application/json"
                },
                body:JSON.stringify({
                    username
                })
            }).then(value=>value.json()).then(value=>{
                if(value.ok === 1){
                    const chat = document.querySelector("#chat");
					document.querySelector("#login").style.display = "none";
					document.querySelector("#room").style.display = "block";
                    document.querySelector("#username").innerHTML = username;
                    // 连接
	                const ws = io.connect("/");
                    // 告诉来房间的人的信息
	                ws.emit("inRoom",username);
                    // 接收进入房间的消息
	                ws.on("inRoomInfo",function(onlineNum,username){
                        document.querySelector("#online").innerHTML = onlineNum;
						chat.value = username+"进入了房间！\n"+chat.value;

	                })
	                // 接收离开房间的消息
                    ws.on("outRoomInfo",function(onlineNum,username){
                        document.querySelector("#online").innerHTML = onlineNum;
                        chat.value = username+"离开了房间！\n"+chat.value;
                    })
	                ws.on("say",function(content){
                        chat.value = content+"\n"+chat.value;3
	                })

	                document.querySelector("#content").onkeyup = function(e){
                        if(e.keyCode === 13){
                            ws.emit("alluser",this.value.trim());
                        }
	                }

                }else{
                    alert(value.msg);
                }
            })
        }

	}
</script>
</html>